package com.zyk.leetcode;

/**
 * @author zhangsan
 * @date 2021/5/1 13:49
 */
public class C1401 {


    // 模拟
    public static int numSteps(String s) {
        char[] str = s.toCharArray();
        int cnt = 0;
        int i = str.length - 1;
        while (i > 0) {
            if (str[i] == '0') {
                i--;
                cnt++;
            } else {     // 10100
                // 1 1 0      00
                int j = i;
                for (; j >= 0; j--, cnt++) {
                    if (str[j] == '1') {
                        str[j] = '0';
                    } else {
                        str[j] = '1';
                        cnt++;
                        break;
                    }
                }
                i = j;
            }
        }
        return str[0] == '0' ? cnt + 1 : cnt;
    }

    // 对数器方法
    public static int numSteps2(String s) {
        int i = Integer.parseInt(s, 2);
        int step = 0;
        while (i != 1) {
            if ((i & 1) == 1) {
                i += 1;
            } else {
                i >>= 1;
            }
            step++;
        }
        return step;
    }


    // for test
    public static void main(String[] args) {
//        String s = "101";
//        System.out.println(numSteps2(s));
//        System.out.println(numSteps(s));

        for (int i = 1; i <= 32; i++) {
            System.out.println(i + " : " + Integer.toBinaryString(i) + " : " + numSteps(Integer.toBinaryString(i)));
            System.out.println(i + " : " + Integer.toBinaryString(i) + " : " + numSteps2(Integer.toBinaryString(i)));
        }

    }
}
